package com.feng.cloud.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.cloud.common.constants.SystemConstant;
import com.feng.cloud.common.request.QueryRequest;
import com.feng.cloud.common.utils.SortUtils;
import com.feng.cloud.system.entity.Log;
import com.feng.cloud.system.mapper.LogMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName LogService
 * @Description TODO
 * @Author Better Feng
 * @Date 2019/12/25 14:02
 * @Version 1.0
 **/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
@AllArgsConstructor
public class LogService extends ServiceImpl<LogMapper, Log> {

    private final LogMapper logMapper;

    @Async(SystemConstant.ASYNC_POOL)
    public void addLog(Log log) {
        logMapper.insert(log);
    }

    public IPage<Log> selectListByPage(QueryRequest request) {
        String userName = request.getValue(Log::getUsername,String.class);
        LambdaQueryWrapper<Log> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(userName)) {
            queryWrapper.like(Log::getUsername, userName);
        }
        String operation = request.getValue(Log::getOperation,String.class);
        if (StringUtils.isNotBlank(operation)) {
            queryWrapper.like(Log::getOperation, operation);
        }
        SortUtils.handleTimeFromTo(request, Log::getCreateTime, queryWrapper);
        Page<Log> page = new Page<>();
        SortUtils.handlePageAndSort(request, page, Log::getCreateTime, SystemConstant.ORDER_DESC);
        return this.baseMapper.selectPage(page, queryWrapper);
    }



    public void deleteLogs(List<String> idList) {
        this.baseMapper.deleteBatchIds(idList);
    }
}
